<?php
/**
 * Created by PhpStorm.
 * User: ma
 * Date: 2017/12/30
 * Time: 14:26
 */

namespace app\index\controller;

use app\common\model\CashWith;
use app\common\model\Configs;
use app\common\model\ShopBank;
use app\common\model\Shop;
use think\Db;
use think\facade\Request;
use think\facade\Session;

class Cash extends Base
{
    /**
     * 商户账户
     */
    public function cash()
    {
        // 商户ID
        $shop_id = Session::get('sp_id','index');
        if(!$shop_id) $this->error('请先登录','index/login');
        $request = $this->request;
        if ($request->isGet()) {

            $model = new Shop();
            $res2 = db('shops')->where('sp_id', $shop_id)->find();
            $res = db('shops')
                ->alias('ss')
                ->leftJoin('cash_with cw', 'ss.sp_id=cw.shop_id')
                ->leftJoin('shop_bank sk', 'sk.sbank_cash_id=cw.c_id')
                ->where('sp_id', $shop_id)
                ->where('label', 2)
                ->field('sp_id,c_order,start_time,c_status,money,sbank_status')
                ->paginate(10, false, []);
            $this->assign('status', 0);
            $this->assign('list2', $res2);
            $this->assign('list', $res);
            return $this->fetch();
        } elseif ($request->isPost()) {
            $startTime = strtotime(Request::post('add_time_begin'));
            $endTime = strtotime(Request::post('add_time_end'));
            $status = $request->param('ord_status');
            $where = array();
            if (!empty($status)) {
                if (!empty($startTime)) {
                    if (!empty($endTime)) {
                        $where[] = [['sbank_status', '=', $status], ['start_time', 'between', [$startTime, $endTime]], ['label', '=', 2], ['sp_id', '=', $shop_id]];

                    }
                }
                $where[] = [['sbank_status', '=', $status], ['label', '=', 2], ['sp_id', '=', $shop_id]];

            }

//            $where1[] = [ ['start_time','between',[$startTime,$endTime]],['label', '=', 2],['sp_id', '=', $shop_id]];
            $model = new Shop();
            $res2 = db('shops')->where('sp_id', $shop_id)->find();
            $res = db('shops')
                ->alias('ss')
                ->leftJoin('cash_with cw', 'ss.sp_id=cw.shop_id')
                ->leftJoin('shop_bank sk', 'sk.sbank_cash_id=cw.c_id')
                ->where($where)
//                ->whereOr($where1)
                ->field('sp_id,c_order,start_time,c_status,money,sbank_status')
                ->paginate(10, false, []);
            $this->assign('status', $status);
            $this->assign('add_time_begin', Request::post('add_time_begin'));
            $this->assign('add_time_end', Request::post('add_time_end'));
            $this->assign('list2', $res2);
            $this->assign('list', $res);
            return $this->fetch();

        }
    }
    /**
     * 提现申请页
     */
    public function requireCash()
    {
        // 商户ID
        $shop_id = Session::get('sp_id','index');
        if(!$shop_id) $this->error('请先登录','index/login');
        $request = $this->request;
        if ($request->isGet()) {
            $model = new Shop();
            $res = db('shops')->where('sp_id', $shop_id)->field('sp_income_rest')->find();
            $this->assign('rest', $res['sp_income_rest']);
            return $this->fetch('cash/requireCash');
        } elseif ($request->isPost()) {
            $verity_code = $request->param('agem_phone');
            $true_code = Session::get('name.code');

            if ($verity_code != $true_code) {
                $this->error('验证码错误', 'cash/cash');
            }

            $data2['shop_id'] = $request->param('shop_id');
            $data2['money'] = $request->param('money_count');
            $data2['c_order'] = 'SP' . date('YmdHis', time()) . rand(1000, 9999);
            $data2['label'] = 2;
            $data2['start_time'] = time();
            $data1['sp_id'] = $request->param('shop_id');
            $data1['sbank_name'] = $request->param('account_name');
            $data1['sbank_account_num'] = $request->param('bank_account');
            $data1['sbank_bank_name'] = $request->param('bank');

            Db::startTrans();
            try {
                $model2 = new CashWith();
                $res2 = $model2->data($data2)->save();
                $data1['sbank_cash_id'] = $model2->c_id;
                $model = new ShopBank();
                $res = $model->data($data1)->save();
                $model3 = new Shop();
                $res3 = $model3->where('sp_id', $data2['shop_id'])->find();
                $data3['sp_income_rest'] = $res3['sp_income_rest'] - $data2['money'];
                $data3['sp_income_freeze'] = $res3['sp_income_freeze'] + $data2['money'];
                $res4 = $model3->isUpdate(true)->save($data3, ['sp_id' => $data2['shop_id']]);
                Db::commit();

            } catch (\Exception $E) {
                Db::rollback();
                $this->error('申请失败，请重试');
            }
            $this->success('申请成功，请耐心等待', 'cash');

        }
    }
    /**
     * 短信发送测试功能
     */
    public function smsPhone()
    {
        $id = $this->request->param('sp_id');
        if (Session::has('name.code')) {
            if (time() - Session::get('name.time') < 60) {
                $return = false;
                return $this->ajaxReturn($return);
            }
        }

        $model = new Shop();
        $phone = db('shops')->where('sp_id', $id)->field('sp_mobile')->find();
        if (!$phone) {
            return $this->error('失败');
        }

        //获取短信配置
        $config = Configs::where('inc_type', 'alisms')->select();
        foreach ($config as $v) {
            $sms[$v['name']] = $v['value'];
        }
        $appid = $sms['sms_appkey'];
        $secret = $sms['sms_secretKey'];
        $phone = $phone['sp_mobile'];
        $signName = $sms['sms_product'];
        $templateCode = $sms['sms_code'];
        $code = rand(1000, 9999);
        $commont = 'sdfas';

        //调用短信发送借口
        $query = sendSms($appid, $secret, $phone, $signName, $templateCode, $code, $commont);
        if ($query) {
            Session::set('name.code', $code);
            Session::set('name.time', time());
            return $query;
        }
    }
    public function ajaxReturn($data, $type = 'json')
    {
        exit(json_encode($data));
    }
    /**
     * 短信发送测试功能
     */
    public function accountInfo()
    {
        // 商户ID
        $shop_id = Session::get('sp_id','index');
        if(!$shop_id) $this->error('请先登录','index/login');
        $res = \db('shops')
            ->alias('ss')
            ->leftJoin('types ts', 'ss.sp_tyid=ts.ty_id')
            ->leftJoin('agent_manage ae', 'ss.sp_agem_id=ae.agem_id')
            ->where('sp_id', $shop_id)
            ->field('ty_name,sp_name,sp_username,sp_mobile,sp_phone,sp_true_name,sp_company,sp_legal_person,sp_bus_license,sp_address,agem_principals,sp_status,sp_create_time,sp_start_time,sp_end_time,sp_appid,sp_openid,sp_audit,sp_audit_time,sp_identity,sp_number,sp_income,sp_income_rest,sp_income_freeze,sp_person_flow,sp_packet_num,sp_packet_account,sp_ratio,ae.agem_principals')
            ->find();
        $this->assign('info', $res);
        return $this->fetch('accountInfo');
    }

    /**
     * 完善信息
     */
    public function infoUpd(){
        // 商户ID
        $shop_id = Session::get('sp_id','index');
        if(!$shop_id) $this->error('请先登录','index/login');
        $model = new Shop();
        // 提交修改
        if(input('get.act') == 'u'){
            $data = input('post.');
            //验证器
            // $validate = $this->validate($data,'Shop');
            // if(!$validate){
            //     return $this->error($validate);
            // }
            //文件是否上传
            $file = $this->request->file('image');
            $logo = $this->request->file('logo');
            // 上传营业执照
            if($file){
                //验证通过，并移动图片
                $fileName = $file->validate(['ext'=>'png,jpg,jpeg'])->move('public/upload/shop');
                if($fileName){
                    $data['sp_bus_license_url']  = $fileName->getPathName();
                }else{
                    return $this->error($file->getError());
                }
            }
            // 上传店铺logo
            if($logo){
                //验证通过，并移动图片
                $fileName = $logo->validate(['ext'=>'png,jpg,jpeg'])->move('public/upload/shoplogo');
                if($fileName){
                    $data['sp_logo_url']  = $fileName->getPathName();
                }else{
                    return $this->error($logo->getError());
                }
            }

            $data['sp_id'] = $shop_id;
            $res = $model->edit($data);
            if($res){
                $this->success('修改成功','cash/accountInfo');
            }else{
                $this->error('修改失败');
            }
        }else{
            // 获取所有的商户分类
            $cates = $model->cates();
            // 商户详情
            $shop = $model->detail($shop_id);

            $this->assign('shop',$shop);
            $this->assign('cates',$cates);
        }

        return $this->fetch('cash/infoUpd');
    }

    /**
     * 店铺轮播
     */
    public function round(){
        // 商户ID
        $shop_id = Session::get('sp_id','index');
        if(!$shop_id) $this->error('请先登录','index/login');
        if($shop_id) $data['sp_id'] = $shop_id;
        // 表单提交
        if(input('get.act') == 'u'){
            $rounds = array();
            // 是否上传
            $files = request()->file('image');
            foreach($files as $file){
                $info = $file->validate(['ext'=>'jpg,jpeg,png'])->move('public/upload/shop');
                if($info){
                    $rounds[] = $info->getPathName();
                }else{
                    // 上传失败获取错误信息
                    echo $file->getError();
                }    
            }
            if(is_array($rounds)){
                $data['sp_round_url'] = implode(',',$rounds);
                // 修改
                $model = new Shop();
                $res = $model->edit($data);
                if($res){
                    $this->success('操作成功');
                }else{
                    $this->error('修改失败');
                }
            }
        }else{
            // 获取轮播图
            $arr = db('shops')->field('sp_round_url')->where('sp_id',$shop_id)->find();
            if($arr){
                $rounds = explode(',',$arr['sp_round_url']);
                $this->assign('rounds',$rounds);
            }
        }
        return $this->fetch('cash/round');
    }

}
